<?php


namespace app\controller;

use app\BaseController;
use app\model\Blogs;
use app\model\Users;
use app\validate\Avatar;
use think\facade\Db;
use think\facade\Filesystem;
use think\facade\Request;
use think\exception\ValidateException;
use think\facade\Session;
use think\facade\View;

class User extends BaseController
{
    // 个人信息页面
    public function infoPage()
    {
        return View::fetch('user/info', ['nav' => 'info',]);
    }

    // 更新个人信息
    public function infoUpdate(Request $request)
    {

        $name = $request::param('name');
        $email = $request::param('email');
        $data = ['name' => $name, 'email' => $email];

        // 验证输入信息
        try {
            validate(\app\validate\User::class)
                ->batch('true')
                ->only(['name', 'email'])
                ->remove('name', 'unique')
                ->remove('email', 'unique')
                ->check($data);
        } catch (ValidateException $e) {
            // 获取错误信息
            $errors = $e->getError();
            $resdata = json(['code' => 400, 'msg' => $errors]);

            // 返回错误信息
            return $resdata;
        }

        // 更新用户数据
        $uid = Session::get('uid');
        $res = Db::table('users')
            ->where('id', $uid)
            ->update([
                'name' => $name,
                'email' => $email,
                'updated_at' => date('Y-m-d h:i:s', time())
            ]);
        if ($res) {
            // 更新session
            Session::set('name', $name);
            Session::set('email', $email);
            // 返回信息
            return json(['code' => 200, 'msg' => '修改成功！']);
        } else {
            return json(['code' => 400, 'msg' => '未做更改']);
        }
    }

    // 头像页面
    public function avatarPage()
    {
        return View::fetch('user/avatar',['nav' => 'avatar',]);
    }

    // 更新头像
    public function avatarUpdate(Request $request)
    {
        // 验证图片
        try {
            $file = $request::file('avatar');
            validate(Avatar::class)->check(['avatar' => $file]);
        } catch (ValidateException $e) {
            $error = $e->getError();
            // 返回错误信息
            return json(['code' => 400, 'msg' => $error]);
        } catch (\Exception $e) {
            return json(['code' => 400, 'msg' => '请选择图片']);
        }
    // 删除原有头像
//    $old_avatar_url = Users::where('id', Session::get('uid'))
//        ->value('avatar');
//    $old_avatar = str_replace('/storage/', '', $old_avatar_url);
//    Filesystem::disk('public')->delete($old_avatar);

    // 保存图片到本地
    $avatar_path = '/storage/'.Filesystem::disk('public')
            ->putFile('avatar', $file);
    $uid = Session::get('uid');

    $avatar_path = str_replace('\\', '/', $avatar_path);

    $res = Db::table('users')
        ->where('id', $uid)
        ->update(['avatar' => $avatar_path]);

    if ($res) {
        return json(['code' => 200, 'msg' => '上传成功']);
    } else {
        return json(['code' => 400, 'msg' => '上传失败']);
    }
    }

    // 用户所有博客页面
    public function blog(Users $users)
    {
        $blogs = $users
            ->where('id', Session::get('uid'))
            ->find()
            ->blogs()
            ->withCount('comments')
            ->order('updated_at', 'desc')
            ->paginate(5);

        $page = $blogs->render();

        return View::fetch('user/blog',[
            'nav' => 'blog',
            'blogs' => $blogs,
            'page' => $page,
        ]);
    }

    public function sginin(){
        echo 11;
    }
}